import React, {useEffect, useMemo, useState,useRef} from 'react'
import {Button, Form, message, Card, Radio, Steps, Input} from 'antd'
import moment from 'moment'
import Styles from './index.less'
import {Basics} from '../components'
import {ClueRecommendationRecord} from '../components/CollectionAccount'
import Tb from '../components/tb'
import EDTB from '../components/eidtable'
import {
	getDitchsettleaccountsDetails,
	insertDitchReplenish,
	processAuditSuccess,
	processDitchList,
	processList,
	updateDitchReplenish,
} from '@/service/merchantCenter/channelSettlement'

import {getFirstChannelType} from '@/service/channel'
import Examine from '@/components/Examine'
import {processRecordSave} from '@/service/common/index'

const {Step} = Steps

export default function Add(props: any) {
	// eslint-disable-next-line react/destructuring-assignment
	const routerQuery = props.location.query

	const pageType = useMemo(() => routerQuery.pageType, [routerQuery])
	const processId = useMemo(() => routerQuery.processId, [routerQuery])
	const orgId:any = useMemo(() => routerQuery.orgId, [routerQuery])
	const examineRef = useRef<any>(null)
	const isEdit = useMemo(() => routerQuery.isEdit, [routerQuery])
	const leaseType = useMemo(
		() => routerQuery?.leaseType?.toString() || false,
		[routerQuery],
	)

	const [loading, setLoading] = useState(false)
	// const [channelCodeList, setChannelCodeList] = useState<any[]>([
	//   { a: 1, b: 2, c: 3, key: '1' },
	//   { a: 11, b: 22, c: 33, key: '2' },
	// ]);
	const [detailRecord, setDetailRecord] = useState<any>({})
	const [basicsForm] = Form.useForm()
	// const [referrerForm] = Form.useForm();

	const [ClueRecommendationRecordList, setClueRecommendationRecordList] =
		useState([])

	const [tableList, setTableList] = useState<any[]>([])

	const [channelTypeOneType, setChannelTypeOneType] = useState([])

	const getChannelTypeOneType = () => {
		getFirstChannelType().then((res: any) => {
			if (res?.data?.length) {
				setChannelTypeOneType(res.data)
			}
		})
	}

	useEffect(() => {
		getChannelTypeOneType()
	}, [])

	useEffect(() => {
		if (pageType) {
			getDitchsettleaccountsDetails({id: routerQuery.id}).then(
				(res: any) => {
					if (res.data) {
						setDetailRecord(res.data)
						setClueRecommendationRecordList(
							res.data.singlePageVOList,
						)
					}
				},
			)
			// geTselectDitchRewardsRecordsList({id: routerQuery.id}).then(
			// 	(res: any) => {
			// 		if (res.data) {
			// 			console.log(res.data)
			// 			setDetailRecord(res.data)
			// 			setClueRecommendationRecordList(
			// 				res.data.singlePageVOList,
			// 			)
			// 		}
			// 	},
			// )
		}
	}, [pageType])

	// const onSave = async () => {
	//   try {
	//     referrerForm.resetFields();
	//     const data = await referrerForm.validateFields();
	//     addDitch
	//     console.log(data, 'data');
	//   } catch (error) {
	//     // eslint-disable-next-line no-console
	//     console.log(error, 'error');
	//   }
	// };
	// eslint-disable-next-line consistent-return
	const onSave = async () => {
		setLoading(true)
		try {
			// const basicsFormData = await basicsForm.validateFields()
			// console.log(basicsForm)
			const newtableList = tableList?.map((item) => ({
				...item,
				rewardOccurrenceDate: moment(item?.rewardOccurrenceDate).format(
					'YYYY-MM-DD HH:mm:ss',
				),
			}))
			if (isEdit === 'true') {
				const res = await updateDitchReplenish({
					settId: routerQuery.id,
					ditchReplenishList: newtableList,
				})
				if (res.success) {
					message.success(res.msg)
					history.go(-1)
				} 
			} else {
				const res = await insertDitchReplenish({
					settId: routerQuery.id,
					ditchReplenishList: newtableList,
				})
				if (res.success) {
					message.success(res.msg)
					history.go(-1)
				} 
			}

			setTimeout(() => setLoading(false), 1000)
		} catch (error) {
			setTimeout(() => setLoading(false), 1000)
			// eslint-disable-next-line no-console
			console.log(error, 'error')
		}
	}

	const [btLoading, setBtLoading] = useState(false)

	const onFinishModal = (values: any) => {
		// eslint-disable-next-line no-param-reassign
		if (values) {
			const newValue  = {...values}
			setBtLoading(true)
			newValue.ids = [routerQuery.id]
			newValue.type = Number(routerQuery.type)
			newValue.message = JSON.stringify({message:newValue.message})
			processAuditSuccess(newValue).then((res: any) => {
				if (res.success) {
					setBtLoading(false)
					message.success(res.msg)
					history.go(-1)
					if(values?.pass ===2){
						processRecordSave({
							bizType: 11,
							bizNo: routerQuery?.id,
							processId,
						})
					}
					
				} else {
					setBtLoading(false)
				}
			})

			setBtLoading(false)
		}
	}

	const [bkfArr, setBkfArr] = useState([])
	const [sjArr, setSjArr] = useState([])

	useEffect(() => {
		processList({id: routerQuery.id}).then((res: any) => {
			if (res.success) {
				setSjArr(res.data || [])
			}
		})
		processDitchList({id: routerQuery.id}).then((res: any) => {
			if (res.success) {
				setBkfArr(res.data || [])
			}
		})
	}, [])

	return (
		<div className={Styles.add}>
			{/* {bkfArr.length && pageType !== 'edit' ? (
				<Card
					id="补扣费审批信息"
					title="补扣费审批信息"
					bordered={false}>
					<Steps
						current={
							bkfArr.findIndex(
								(item: any) => item.nodeType === 2,
							) === -1
								? bkfArr.length - 1
								: bkfArr.findIndex(
										(item: any) => item.nodeType === 2,
								  )
						}>
						{bkfArr.map((item: any, index: any) => (
							<Step
								title={item.activityName}
								description={
									<div>
										{(index !== 0 ||
											item.activityName !== '结束') && (
											<div>{item.assignee || ' '}</div>
										)}
										<div>{item.startTime}</div>
										{(index !== 0 ||
											item.activityName !== '结束') && (
											<div>
												{
													[
														'',
														'已审核',
														'待审核',
														'已作废',
														'未开始',
													][item.nodeType]
												}
											</div>
										)}
										{(index !== 0 ||
											item.activityName !== '结束') && (
											<div>{`备注：${item.message}`}</div>
										)}
									</div>
								}
							/>
						))}
					</Steps>
				</Card>
			) : (
				<></>
			)} */}
			{orgId && processId && pageType !== 'edit' ?(
				<Card id="审批" title="审批" bordered={false}>
					<Examine
						ref={examineRef}
						examineType={false}
						orgId={orgId}
						processInstanceId={processId}
						bizType={11}
						bizNo={routerQuery.id}
						
					/>
				</Card>
				
			):(<></>)}
			
			{/* {sjArr.length && pageType !== 'edit' ? (
				<Card id="结算审批信息" title="结算审批信息" bordered={false}>
					<Steps
						current={
							sjArr.findIndex(
								(item: any) => item.nodeType === 2,
							) === -1
								? sjArr.length - 1
								: sjArr.findIndex(
										(item: any) => item.nodeType === 2,
								  )
						}>
						{sjArr.map((item: any, index: any) => (
							<Step
								title={item.activityName}
								description={
									<div>
										{(index !== 0 ||
											item.activityName !== '结束') && (
											<div>{item.assignee || ' '}</div>
										)}
										<div>{item.startTime}</div>
										{(index !== 0 ||
											item.activityName !== '结束') && (
											<div>
												{
													[
														'',
														'已审核',
														'待审核',
														'已作废',
														'未开始',
													][item.nodeType]
												}
											</div>
										)}
										{(index !== 0 ||
											item.activityName !== '结束') && (
											<div>{`备注：${item.message}`}</div>
										)}
									</div>
								}
							/>
						))}
					</Steps>
				</Card>
			) : (
				<></>
			)} */}

			{routerQuery.type ? (
				<Card id="审批" title="审批" bordered={false}>
					<Form
						style={{width: '400px'}}
						name="basic"
						onFinish={onFinishModal}
						autoComplete="off">
						<Form.Item
							label="审批状态"
							name="pass"
							rules={[
								{
									required: true,
									message: 'Please input your username!',
								},
							]}>
							<Radio.Group>
								<Radio value={1}> 审批通过 </Radio>
								<Radio value={2}> 审批驳回 </Radio>
							</Radio.Group>
						</Form.Item>

						<Form.Item label="处理意见" name="message">
							<Input />
						</Form.Item>

						<Form.Item style={{textAlign: 'right'}}>
							<Button
								type="primary"
								htmlType="submit"
								loading={btLoading}>
								提交审批
							</Button>
						</Form.Item>
					</Form>
				</Card>
			) : (
				<></>
			)}
			<Basics
				pageType={pageType}
				basicsForm={basicsForm}
				detailRecord={detailRecord}
			/>
			{leaseType === '1' || pageType === 'edit' ? (
				<ClueRecommendationRecord
					// clueId={1}
					pageType={pageType}
					detailRecord={ClueRecommendationRecordList}
				/>
			) : (
				<></>
			)}

			<Tb
				clueId={routerQuery.id}
				pageType={pageType}
				channelTypeOneType={channelTypeOneType}
			/>
			{leaseType === '1' || pageType === 'edit' ? (
				<EDTB
					clueId={routerQuery.id}
					pageType={pageType}
					detailRecord={detailRecord}
					tableList={tableList}
					setTableList={setTableList}
					channelTypeOneType={channelTypeOneType}
				/>
			) : (
				<></>
			)}

			<div className={Styles.operation}>
				{pageType === 'edit' && (
					<Button
						type="primary"
						htmlType="submit"
						loading={loading}
						onClick={() => {
							onSave()
						}}>
						保存
					</Button>
				)}

				<Button
					style={{marginLeft: '5px;'}}
					onClick={() => {
						// eslint-disable-next-line no-restricted-globals
						history.go(-1)
					}}>
					取消
				</Button>
			</div>
		</div>
	)
}
